﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace YuShiManageSystem.COM
{
    [StructLayout(LayoutKind.Sequential)]
    public static unsafe class IC
    {
        //对设备进行初始化
        [DllImport("Mwic_32.dll", EntryPoint = "auto_init", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int auto_init(int port, int baud);
        //设备密码格式
        [DllImport("Mwic_32.dll", EntryPoint = "setsc_md", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int setsc_md(int icdev, int mode);
        //获取设备当前状态
        [DllImport("Mwic_32.dll", EntryPoint = "get_status", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern Int16 get_status(int icdev, Int16* state);
        //关闭设备通讯接口
        [DllImport("Mwic_32.dll", EntryPoint = "ic_exit", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int ic_exit(int icdev);
        //使设备发出蜂鸣声
        [DllImport("Mwic_32.dll", EntryPoint = "dv_beep", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int dv_beep(int icdev, int time);
        //向IC卡中写数据
        [DllImport("Mwic_32.dll", EntryPoint = "swr_4442", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int swr_4442(int icdev, int offset, int len, char* w_string);
        //核对卡密码 
        [DllImport("Mwic_32.dll", EntryPoint = "csc_4442", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
        private static extern Int16 Csc_4442(int icdev, int len, [MarshalAs(UnmanagedType.LPArray)] byte[] p_string);
        //读卡中数据
        [DllImport("Mwic_32.dll", EntryPoint = "srd_4442", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        private static extern int srd_4442(int icdev, int offset, int len, [MarshalAs(UnmanagedType.LPArray)] byte[] r_string);
        /// <summary>
        /// 写入IC卡
        /// </summary>
        /// <param name="cId">IC卡号</param>
        /// <param name="uId">会员身份证号</param>
        /// <param name="flag">门店编号</param>
        /// <returns>成功返回Ture,否则返回false</returns>
        public static bool Write(string cId,string uId,string flag)
        {   
            //初始化读卡器
            int icdev = auto_init(0, 9600);
            if (icdev < 0)
            {   
                YSMessage.Show("端口初始化失败,请检查接口线是否连接正确。");
                return false;
            }
            int md = setsc_md(icdev, 1); //设备密码格式
            unsafe 
            {
                Int16 status = 0;
                Int16 result = 0;
                result = get_status(icdev, &status);
                if (result != 0)
                {             
                    int d1 = ic_exit(icdev);   //关闭设备
                    YSMessage.Show("设备当前状态错误！");
                    return false;
                }
                if (status != 1)
                {
                    int d2 = ic_exit(icdev);   //关闭设备
                    YSMessage.Show("请插入ＩＣ卡");
                    return false;
                }
            }

            unsafe
            {
                //卡的密码默认为6个f（密码为：ffffff），1个f的16进制是15,两个f的16进制是255
                byte[] pwd = new byte[3] { 255, 255, 255 };
                Int16 checkIC_pwd = Csc_4442(icdev, 3, pwd);
                //int beep = IC.dv_beep(icdev, 20);
                //MessageBox.Show(checkIC_pwd.ToString());
                //IC.ic_exit(icdev);
                //return;
                if (checkIC_pwd < 0)
                {   
                    YSMessage.Show("ＩＣ卡密码错误！");
                    return false;
                }
                char c = 'a';
                int write = -1;
                if (uId.Length==15) uId+="FFF";
                string s=cId+uId+flag;

                for (int j = 0; j < s.Length; j++)
                {
                    c = Convert.ToChar(s.Substring(j, 1));
                    write = swr_4442(icdev, 32 + j, 1, &c);
                }                
                if (write == 0)
                {
                    dv_beep(icdev, 20);  //发出蜂鸣声
                    int d = ic_exit(icdev);  //关闭设备
                    YSMessage.Show("会员信息已成功写入ＩＣ卡中！");
                    return true;
                }

                else
                {
                    int d = IC.ic_exit(icdev);  //关闭设备
                    YSMessage.Show("写入ＩＣ卡失败！");
                    return false;
                }
            }
        }
        /// <summary>
        /// 从IC卡读取数据
        /// </summary>
        /// <returns>成功返回读到的字符串，否则返回null</returns>
        public static string Read()
        { 
             //初始化读卡器
            string str=null;
            int icdev = auto_init(0, 9600);
            if (icdev < 0)
            {
                YSMessage.Show("端口初始化失败,请检查接口线是否连接正确。");
                return str;
            }
            int md = setsc_md(icdev, 1); //设备密码格式
            unsafe 
            {
                Int16 status = 0;
                Int16 result = 0;
                result = get_status(icdev, &status);
                if (result != 0)
                {
                    int d1 = ic_exit(icdev);   //关闭设备
                    YSMessage.Show("设备当前状态错误！");
                    return str;
                }
                if (status != 1)
                {
                    int d2 = ic_exit(icdev);   //关闭设备
                    YSMessage.Show("请插入ＩＣ卡");
                    return str;
                }
            }

            unsafe
            {
                //卡的密码默认为6个f（密码为：ffffff），1个f的16进制是15,两个f的16进制是255
                byte[] pwd = new byte[3] { 255, 255, 255 };
                Int16 checkIC_pwd = Csc_4442(icdev, 3, pwd);
                if (checkIC_pwd < 0)
                {
                    YSMessage.Show("ＩＣ卡密码错误！");
                    return str;
                }
            }
            unsafe
            {

                byte[] b=new byte[11+18+6] ;

                int read = -1;

                //for (int j = 0; j < 6; j++)
                //{

                //    read = IC.srd_4442(icdev, 33 + j, 1, &str);

                //    textBox1.Text = textBox1.Text + Convert.ToString(str);

                //}
               read = srd_4442(icdev, 32, 11+18+6, b);
               str = System.Text.Encoding.ASCII.GetString(b);
               if (read == 0)
                   MessageBox.Show("ＩＣ卡中数据读取成功！");
            }
            int d = IC.ic_exit(icdev);  //关闭设备
            return str;        
        }
    }
}
